package mytest;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Enumeration;

@WebServlet("/deleteContact")
public class DeleteContactServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String paramValue = request.getParameter(paramName);
            System.out.println("Parameter Name: " + paramName + ", Value: " + paramValue);
        }
        String id = request.getParameter("contactId");
        Connection conn;
        PreparedStatement ps;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/contact", "root", "root123");
            ps = conn.prepareStatement("DELETE FROM contacts WHERE id = ?");
            ps.setInt(1, Integer.parseInt(id));
            ps.executeUpdate();

            // 重定向到联系人列表页面
            response.sendRedirect("/contact");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

